package com.liujun.microserver.auth2.authserver.jdbc.config;

import java.util.concurrent.TimeUnit;

import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.provider.ClientDetailsService;
import org.springframework.security.oauth2.provider.client.JdbcClientDetailsService;
import org.springframework.security.oauth2.provider.token.DefaultTokenServices;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.JdbcTokenStore;

/**
 * doc:进行auth2的授权服务器配制， 此作为单独的授权服务器
 * 
 * @author liujun
 * @date 2018/07/01
 */
@Configuration
@EnableAuthorizationServer
public class Oauth2AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {

	/**
	 * 认证管理器，当你选择了资源所有者密码（password）授权类型的时候，请设置这个属性注入一个 AuthenticationManager 对象
	 */
	@Autowired
	private AuthenticationManager authManager;

	/**
	 * 数据库操作
	 */
	@Autowired
	private DataSource datasource;

	/**
	 * 令牌业务
	 */
	@Autowired
	private TokenStore tokenStore;

	/**
	 * 负责从存储仓库中读取数据
	 */
	private ClientDetailsService clientDetailsService;

	@Bean
	public TokenStore tokenStore() {
		return new JdbcTokenStore(datasource);
	}

	/**
	 * 
	 * @return
	 */
	@Bean
	public ClientDetailsService clientDetails() {
		return new JdbcClientDetailsService(datasource);
	}

	@Override
	public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
		// 设置认证管理器
		endpoints.authenticationManager(authManager);
		// 配制 takstore
		endpoints.tokenStore(tokenStore);

		// 配制tokenServer参数
		DefaultTokenServices tokenServer = new DefaultTokenServices();
		// 令牌
		tokenServer.setTokenStore(endpoints.getTokenStore());
		// 是否支持刷新令牌
		tokenServer.setSupportRefreshToken(false);
		// 负责从存储仓库中读取数据
		tokenServer.setClientDetailsService(endpoints.getClientDetailsService());
		//
		tokenServer.setTokenEnhancer(endpoints.getTokenEnhancer());
		// 配制时间
		tokenServer.setAccessTokenValiditySeconds((int) TimeUnit.DAYS.toSeconds(30));

		endpoints.tokenServices(tokenServer);
	}

	@Override
	public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
		clients.withClientDetails(clientDetailsService);
	}

}
